import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
import Notify from '@vant/weapp/notify/notify';
import { clearUserLocalStorage, userRequest } from "../../../../utils/util";
const { authorization } = require('../../../../utils/location')
const app = getApp();


Page({

    /**
     * 页面的初始数据
     */
    data: {
        orders: [],
        markers: [],
        selected_ids: [],
        main_order_ids: [],
        select_all_status: false,
        show_upload: true, //显示上传
        deletable: true, //允许删除
        max_upload_size: 1048576 * 2,
        count: 0,
        area: '', //获取区域
        scale: 12.1,
        activeNames: ['1'],// 打开信息 按钮
        latitude: 0,   //获取当前位置
        longitude: 0,
        review_checked: true,
        image: '/templates/deliver/img/business.png',

        current_order_id: '',
        current_order_no: '',
        current_order_remark: '',
        current_delivery_photo: [],

        //是否显示面板指示点
        indicator_dots: true,
        autoplay: false, //是否自动切换
        interval: 5000, //自动切换时间间隔
        duration: 500, //滑动动画时长
        color: '#ffffff', //当前选中的指示点颜色
        height: '',
        activeName: '1',
        show_popup: false,
        afterOrder: [],
        deliver_amount: 0,
        review_status: 'approved',
        customafterOrder: {},
        currentIndex: null,
        // isPicker: false,
        new_delivery_man_id: 0,

    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        let now = (new Date().getTime()) / 1000;
        let expiration_time = app.session.expiration_time ?? 0
        if (now > expiration_time) {
            console.log('已过登录有效期!')
            app.session = {}
            clearUserLocalStorage()
            wx.reLaunch({
                url: '/pages/selectID/selectID',
            })
        }

        console.log('session:', app.session)


        let current_delivery_man_id = app.session.current_delivery_man_id ?? 0
        let current_delivery_district_id = app.session.current_delivery_district_id ?? 0
        let delivery_man_list = app.session.delivery_man_list
        let delivery_district_list = app.session.delivery_district_list

        let access_token = wx.getStorageSync('access_token')
        let level = wx.getStorageSync('level')
        let delivery_district = wx.getStorageSync('delivery_district')
        let DeliveyManList = delivery_man_list.map(item => item.text);
        console.log(DeliveyManList)
        this.setData({
            access_token: access_token,

            delivery_district: delivery_district,
            delivery_district_list: delivery_district_list,
            delivery_man_list: delivery_man_list,
            current_delivery_district_id,
            level: level,
            current_delivery_man_id,
            DeliveyManList
        })
        this.get_waiting_review()

    },
    onPickerCancel() {
        this.setData({
            new_delivery_man_id: 0,
            isPicker: false
        })

    },
    // 打印售后单
    async getGoodsSummary(e) {
        const { order_no } = e.currentTarget.dataset;
        const header = {
            'Content-Type': 'application/json',
            'x-api-key': this.data.access_token
        }
        const data = {
            order_no: order_no,
            print: true
        }
        const url = app.globalData.API + '/delivery/index/print-sales'
        try {
            wx.showLoading({
                title: '正在打印...'
            })
            const response = await userRequest(url, 'POST', data, header)
            console.log(response)
            wx.hideLoading()
            if (response.code === 200) {
                Toast.success('打印成功');
            }
        } catch (e) {
            console.log(e)
        }
    },
    onPickerConfirm(e) {
        const { value } = e.detail;
        console.log(value)
        const deliveryMan = this.data.delivery_man_list.find(
            man => man.text === value
        );

        this.setData({
            new_delivery_man_id: deliveryMan.value,
            // isPicker: false
        })


    },
    // onPickerChange(e) {
    //     // const { picker, value, index } = e.detail;
    //     // console.log('onPickerChange', e.detail);

    // },
    // 切换
    onChange(event) {
        this.setData({
            activeName: event.detail,
        });
    },
    // changeDelivery(e) {
    //     const { index } = e.currentTarget.dataset
    //     console.log(this.data.isPicker)
    //     this.setData({
    //         isPicker: true
    //     })

    // },
    onswitchChange({ detail }) {
        // console.log(detail)
        this.setData({ review_checked: detail });
    },
    getDeliveryManText(delivery_man_id) {
        // console.log("----------", delivery_man_id)
        const deliveryMan = this.data.delivery_man_list.find(
            man => man.delivery_man_id === delivery_man_id
        );
        return deliveryMan ? deliveryMan.text : '未知司机';
    },
    // onTapMarker(e) {
    //     const markerId = parseInt(e.detail.markerId)
    //     const markers = this.data.markers;

    //     console.log(markerId)
    //     const marker = markers.find(m => m.id === markerId); // 根据地图标记的 id 找到对应的 marker
    //     console.log(marker)
    //     if (marker) {
    //         const query = wx.createSelectorQuery();
    //         query.select(marker.select_id).boundingClientRect(); // 根据订单 id 找到对应的卡片
    //         query.exec(function(res) {
    //             console.log('res', res)
    //             const cardRect = res[0];
    //             if (cardRect) {
    //                 wx.pageScrollTo({
    //                     scrollTop: cardRect.top,
    //                 });
    //             }
    //         });
    //     }
    // },
    // parseJsonOrEmptyArray(jsonString) {
    //     try {
    //         const parsed = JSON.parse(jsonString);
    //         if (Array.isArray(parsed)) {
    //             // 检查数组元素的结构，并进行转换
    //             return parsed.map(item => {
    //                 if (typeof item === 'object' && 'url' in item) {
    //                     return item; // 已经是 { url: 'https://xxxxx' } 格式
    //                 } else if (typeof item === 'object' && item.url) {
    //                     return item.url; // 处理 { url: { url: 'https://xxxxx' } } 格式
    //                 } else {
    //                     return {}; // 无效的对象格式，返回空对象
    //                 }
    //             });
    //         } else {
    //             return [];
    //         }
    //     } catch (e) {
    //         return [];
    //     }
    // },
    // ballPopup(e) {

    //     let that = this
    //     let index = parseInt(e.currentTarget.dataset.index)

    //     let current_order_id = e.currentTarget.dataset.order_id //获取传递的id参数
    //     let current_order = this.data.orders[index];
    //     console.log(current_order,current_order_id)
    //     console.log(this.data.current_order)
    //     this.setData({
    //         show_popup: true,
    //         current_order_id,
    //         current_order
    //     }) //打开弹窗
    // 	},
    onClose() {
        console.log('123')
        this.setData({ show_popup: false });
    },

    handleDelOrder(e) {
        console.log(e)
        const { index, order_id, order_no } = e.currentTarget.dataset
        this.data.orders.splice(index, 1);
        this.setData({
            orders: this.data.orders
        });
    },
    async handleReviewOrder(e) {
        // let {review_status,review_checked,delived_index}= this.data
        console.log(e)
        let that = this
        let { status: review_status, index, deliver_amount } = e.currentTarget.dataset
        let { access_token } = this.data
        let current_order = this.data.orders[index];
        console.log(review_status, index, current_order, deliver_amount)
        let header = {
            'Content-Type': 'application/json',
            "x-api-key": access_token
        };
        let url = app.globalData.API + '/delivery/index/review-delivery-order';
        try {
            const res = await userRequest(url, 'POST', {
                deliver_amount,
                review_status,
                current_order
            }, header);
            console.log(res)
            if (res.code == 200) {
                console.log(res)
                // 根据状态更新UI
                // 根据状态更新UI
                let message = review_status === 'approved' ? '审核通过' : '已标记为无效订单';
                let type = review_status === 'approved' ? 'success' : 'warning';
                Toast({
                    type: type,
                    message: message,
                    onClose: () => {
                        this.data.orders.splice(currentIndex, 1);
                        // console.log(this.data.orders.length)
                        //let orders = this.data.orders
                        this.setData({ orders: this.data.orders }, () => {
                            this.get_waiting_review()
                            // this.setData({ show_popup: false });
                        });
                    },
                });
                // Notify({
                //     type: type,
                //     message: message,
                //     onClose: () => {
                //         // 提示关闭后重新加载数据
                //         let orders = this.data.orders.filter((item, i) => i !== index);
                //         this.setData({ orders }, () => {
                //             this.get_waiting_review();
                //         });
                //     }
                // });

            } else {
                throw new Error(res.data.message || '审核失败');
            }

        } catch (error) {
            console.error('审核出错:', error);
            Notify({ type: 'danger', message: error.message });
        }

    },
    reviewOrder(e) {
        console.log(e)
        let { index } = e.currentTarget.dataset
        let customafterOrder = this.data.afterOrder[index];
        this.setData({
            show_popup: true,
            customafterOrder,
            currentIndex: index
        }) //打开弹窗
        return false;
    },
    async handleAfterOrder(e) {
        console.log(e)
        // let current_order = current_order
        let { customafterOrder, currentIndex, new_delivery_man_id } = this.data
        console.log(customafterOrder, currentIndex)

        console.log(Object.keys(customafterOrder).length != 0)
        if (Object.keys(customafterOrder).length != 0) {
            let header = {
                'Content-Type': 'application/json',
                "x-api-key": this.data.access_token
            };
            const { review_checked } = this.data
            let url = app.globalData.API + '/delivery/index/review-delivery-order';
            try {
                const res = await userRequest(url, 'POST', {
                    deliver_fee: review_checked ? 3 : 0,
                    review_status: "approved",
                    current_order: customafterOrder,
                    new_delivery_man_id: new_delivery_man_id ? new_delivery_man_id : 0,
                }, header);
                console.log(res)
                if (res.code == 200) {
                    Toast({
                        type: 'success',
                        message: '审核通过',
                        onClose: () => {
                            this.data.orders.splice(currentIndex, 1);
                            console.log(this.data.orders.length)
                            this.setData({ orders: this.data.orders, show_popup: false });
                            //let orders = this.data.orders
                            // this.setData({ orders }, () => {
                            //     this.get_waiting_review()
                            //     this.setData({ show_popup: false });
                            // });
                        },
                    });

                    // Notify({
                    //     type: 'success',
                    //     message: "审核通过",
                    //     onClose: () => {
                    //         // 提示关闭后重新加载数据
                    //         this.data.orders.splice(currentIndex, 1);
                    //         console.log(this.data.orders.length)
                    //         //let orders = this.data.orders
                    //         this.setData({ orders }, () => {
                    //             this.get_waiting_review()
                    //             this.setData({ show_popup: false });
                    //         });
                    //     }
                    // });
                } else {
                    throw new Error(res.data.message || '审核失败');
                }

            } catch (error) {
                console.error('审核出错:', error);
                Notify({ type: 'danger', message: error.message });
            }
        } else { Notify({ type: 'danger', message: '暂无售后单' }) }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {



    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {



    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },



    // 预览图片方法
    previewImage(e) {
        const currentUrl = e.currentTarget.dataset.url; // 当前点击的图片 URL
        const urls = [currentUrl]; // 所有图片的 URL 数组

        wx.previewImage({
            current: currentUrl, // 当前显示图片的 HTTP 链接
            urls: urls // 需要预览的图片 HTTP 链接列表
        });
    },

    async get_waiting_review() {
        const that = this
        let current_delivery_man_id = that.data.current_delivery_man_id
        let current_delivery_district_id = that.data.current_delivery_district_id
        let delivery_status = 1

        // await that.get_current_location()
        wx.request({
            url: app.globalData.API + '/delivery/index/get-waiting-review-orders',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": this.data.access_token,
            },
            method: "POST",
            data: {
                current_delivery_district_id,
                current_delivery_man_id,
                delivery_status
            },
            success(res) {
                if (res.data.code == 200) {
                    let orders = res.data.data.orders
                    console.log(orders)
                    if (orders.length > 0) {

                        let markers = []
                        for (let i = 0; i < orders.length; i++) {
                            // const longitude = orders[i].longitude; // 经度
                            // const latitude = orders[i].latitude; // 纬度
                            // orders[i].latitude = latitude
                            // orders[i].longitude = longitude

                            orders[i].delivery_merge_id = parseInt(orders[i].delivery_merge_id)
                            // orders[i].distance = that.getDistance(latitude, longitude, that.data.latitude, that.data.longitude)
                            orders[i].delivery_photo = JSON.parse(orders[i].delivery_photo)

                            // console.log(orders[i].delivery_photo)
                        }

                        let main_order_ids = [];
                        for (let i = 0; i < orders.length; i++) {
                            if (orders[i].delivery_merge_id === 0) {
                                main_order_ids.push(orders[i].order_id)
                                markers.push({
                                    iconPath: "../../img/icon-hc.png",
                                    id: 900000000 + parseInt(orders[i].order_id),
                                    order_id: orders[i].order_id,
                                    select_id: `#card-${orders[i].order_id}`,
                                    latitude: orders[i].latitude,
                                    longitude: orders[i].longitude,
                                    width: 23,
                                    height: 23,

                                    nearbyCount: 0,
                                    nearMarkers: [],
                                    nearMarkersInfo: [],

                                    callout: {
                                        content: orders[i].contact + '' + (i + 1),
                                        store_name: orders[i].contact,
                                        fontSize: 14,
                                        padding: true,
                                        color: '#444',
                                        display: 'ALWAYS',
                                        textAlign: 'center',
                                        borderRadius: 5,
                                        bgColor: '#ffffff'
                                    },
                                })
                            }
                        }
                        markers.forEach(marker => {
                            marker.callout.content += ` (${marker.nearbyCount})`;
                        });
                        let rdOrders = orders.filter(item => item.order_no.startsWith('RD'));
                        orders = orders.filter(item => item.order_no.startsWith('XD'));
                        that.setData({
                            markers: markers,
                            orders: orders,
                            selected_ids: [],
                            main_order_ids,
                            afterOrder: rdOrders

                        })
                    } else {
                        wx.showToast({
                            title: res.message,
                            icon: 'error',
                            duration: 2000
                        });
                    }
                    // 使用 filter 方法筛选出订单号以 RD 开头的订单

                    Notify({
                        type: 'success',
                        message: '数据加载完成'
                    });


                }
            }
        })
    },


    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        //this.get_waiting_delivery()
        //wx.stopPullDownRefresh()

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },






    // orderBydata(event){
    //     var order_id = event.target.dataset.id;
    //     var name = event.target.dataset.name;
    //     wx.navigateTo({
    //         url: '/templates/deliver/pages/order/order?order_id='+ order_id+'&name='+name,
    //     })
    // }
})
